// import { userLogoutUsingPost } from '@/services/backend/userController';
import avatar from '@/assets/img/avatar/avatar.jpg';
import { LogoutOutlined, SettingOutlined } from '@ant-design/icons';
import { history, Link, useModel } from '@umijs/max';
import { Avatar, Button, message, Space } from 'antd';
import { stringify } from 'querystring';
import type { MenuInfo } from 'rc-menu/lib/interface';
import React, { useCallback } from 'react';
import { flushSync } from 'react-dom';
import HeaderDropdown from '../HeaderDropdown';

export type GlobalHeaderRightProps = {
  menu?: boolean;
  children?: React.ReactNode;
};

export const AvatarName = () => {
  const {initialState} = useModel('@@initialState');
  const {currentUser} = initialState || {};
  return <span className="anticon">{currentUser?.username}</span>;
};

export const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({menu}) => {
  /**
   * 退出登录，并且将当前的 url 保存
   */
  const loginOut = async () => {
    // await userLogoutUsingPost();
    message.success('退出成功');
    const {pathname, search} = window.location;
    const urlParams = new URL(window.location.href).searchParams;
    /** 此方法会跳转到 redirect 参数所在的位置 */
    const redirect = urlParams.get('redirect');
    // Note: There may be security issues, please note
    if (window.location.pathname !== '/user/login' && !redirect) {
      history.replace({
        pathname: '/user/login',
        search: stringify({
          redirect: pathname + search,
        }),
      });
    }
  };

  const {initialState, setInitialState} = useModel('@@initialState');

  const onMenuClick = useCallback(
    (event: MenuInfo) => {
      const {key} = event;
      if (key === 'logout') {
        flushSync(() => {
          setInitialState((s) => ({...s, currentUser: undefined}));
        });
        loginOut();
        return;
      } else if (key === 'info') {
        flushSync(() => {
          setInitialState((s) => ({...s, currentUser: undefined}));
        });
        history.push('/account/info');
        return;
      } else if (key === 'set') {
        console.log('enter 基础配置')
        history.push('/basicConfiguration');
        return;
      }

      history.push(`/account/${key}`);
    },
    [setInitialState],
  );

  const {currentUser} = initialState || {};

  if (!currentUser) {
    return (
      <Link to="/user/login">
        <Button type="primary" shape="round" size="small">
          登录
        </Button>
      </Link>
    );
  }

  const menuItems = [
    // ...(menu
    //   ? [
    //       {
    //         key: 'center',
    //         icon: <UserOutlined />,
    //         label: '个人中心',
    //       },
    //       {
    //         key: 'info',
    //         icon: <SettingOutlined />,
    //         label: '个人设置',
    //       },
    //       {
    //         type: 'divider' as const,
    //       },
    //     ]
    //   : []),
    {
      key: 'set',
      icon: <SettingOutlined />,
      label: '基础配置',
    },
    {
      key: 'logout',
      icon: <LogoutOutlined/>,
      label: '退出登录',
    },
  ];

  return (
    <HeaderDropdown
      menu={{
        selectedKeys: [],
        onClick: onMenuClick,
        items: menuItems,
      }}
    >
      <Space>
        <Avatar size="small" src={avatar}/>
        <span className="anticon">{currentUser?.username ?? '无名氏'}</span>
      </Space>
    </HeaderDropdown>
  );
}
  ;
